//
//  CZRefreshControl.swift
//  WeiBo
//
//  Created by Apple on 16/9/7.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit


//  当前控件的高度
private let CZRefreshControlHeight: CGFloat = 50


//  封装下拉刷新控件
class CZRefreshControl: UIControl {

    //  刷新状态的枚举
    enum CZRefreshControlState {
        //  下拉刷新状态
        case Normal
        //  松手就刷新状态
        case Pulling
        //  正在刷新的状态
        case Refreshing
    }
    
    //  当前控件的刷新状态
    var currentRefreshState: CZRefreshControlState = .Normal {
        didSet {
            switch currentRefreshState {
            case .Normal:
                //  下拉刷新状态
                print("normal")
                //  箭头显示
                iconImageView.isHidden = false
                //  风火轮停止
                indicatorView.stopAnimating()
                
                
                //  重置之前的位置，前程上次是正在刷新
                
                UIView.animate(withDuration: 0.25, animations: { 
                    //  重置
                    self.iconImageView.transform = CGAffineTransform.identity
                    }, completion: { (_) in
                        
                        if oldValue == .Refreshing {
                            UIView.animate(withDuration: 0.25, animations: {
                                self.currentScrollView?.contentInset.top -= CZRefreshControlHeight
                            })
                        }
                        
                })
                
                
                //  文字改变
                messageLabel.text = "下拉刷新"
                
                
                
                
            case .Pulling:
                //  松手就刷新
                print("pulling")
                
                //  箭头调转
                UIView.animate(withDuration: 0.25, animations: { 
                    self.iconImageView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
                //  文字改变
                messageLabel.text = "松手就刷新"
                
                
                
                
            case .Refreshing:
                //  正在刷新
                print("refreshing")
                
                //  开启风火轮
                indicatorView.startAnimating()
                //  隐藏下拉箭头
                iconImageView.isHidden = true
                //  文字改成正在刷新
                messageLabel.text = "正在刷新"
                
                //  设置内容显示间距
                UIView.animate(withDuration: 0.25, animations: { 
                    self.currentScrollView?.contentInset.top += CZRefreshControlHeight
                })
                
                //  发送事件
                sendActions(for: .valueChanged)
            
                
            }
        }
    }
    
    //  当前滚动视图
    var currentScrollView: UIScrollView?
    
    // MARK: --懒加载控件
    //  下拉箭头
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //  风火轮
    private lazy var indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    //  消息文本
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 11)
        label.text = "下拉刷新"
        label.textColor = UIColor.gray
        return label
    }()
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    private func setupUI() {
        
        backgroundColor = UIColor.yellow
        
        addSubview(iconImageView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false

        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal, toItem: iconImageView, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerY, relatedBy: .equal, toItem: iconImageView, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .leading, relatedBy: .equal, toItem: iconImageView, attribute: .trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
    }
    
    //  监听tableview的滚动，需要获取到父视图
    //  在当前视图将要添加到父视图的时候回执行该方法
    override func willMove(toSuperview newSuperview: UIView?) {
        
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        
        //  代码执行到此，父视图是可以滚动的，设置当前视图的宽度
        self.frame.size.width = scrollView.frame.size.width
        self.frame.size.height = CZRefreshControlHeight
        self.frame.origin.y = -CZRefreshControlHeight
        
        
        
        //  使用kvo监听滚动视图
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        
        currentScrollView = scrollView
        
        
    }
    
    //  kvo监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let contentOffsetY = currentScrollView!.contentOffset.y
        
        
        //  计算临界点
        //  内容显示的位置距离frame原点的距离使用contentInset.top + 自身的高度 才能显示出来
        let maxY = -(currentScrollView!.contentInset.top + CZRefreshControlHeight)
        
        //  拖动状态下
        if currentScrollView!.isDragging {
            if contentOffsetY < maxY && currentRefreshState == .Normal {
                currentRefreshState = .Pulling
                print("松手就刷新")
            } else if contentOffsetY >= maxY && currentRefreshState == .Pulling {
                currentRefreshState = .Normal
                print("下拉刷新")
            }
        } else {
            //  没有拖动
            if currentRefreshState == .Pulling {
                currentRefreshState = .Refreshing
                print("正在刷新")
            }
        }
        
        
    }
    
    //  结束刷新的方法
    func endRefreshing() {
        currentRefreshState = .Normal
    }
    
    
    
    deinit {
        //  移除kvo
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    

}
